package com.store.app.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.TaskWillSubmitDetialsListAdapter;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.SubTaskDetailsBean;
import com.store.app.bean.TaskDetailsListBean;
import com.store.app.bean.TaskHeadBean;
import com.store.app.bean.TaskLogBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.utils.UtilsBitmap;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2017/3/7.
 * 待提交任务详情页面
 */
public class WillSubmitTaskDetailsActivity extends BaseActivity implements IOnHttpListener {
    private ImageView public_ll_return;
    private TextView tvTitle;
    private ListView lv;
    private TaskWillSubmitDetialsListAdapter adapter;
    private List<TaskDetailsListBean> taskDetailsListBeanList = new ArrayList<>();
    private List<TaskLogBean> logBeanList = new ArrayList<>();
    private LinearLayout ll_cancel;
    private LinearLayout ll_submit;
    private Dialog dialog;
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static String localTempImageFileName = "";
    private BitmapBean bitmapBean;
    private int tempIndex = 0;
    private int chooseIndex = 0;

    private NetRequest netRequest;

    private String processing_id;
    private boolean ifMustMod =true;//是否必须全部修改，默认第一次没有submitted_date的时候是要求他得全部改过后的。
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_will_submit_task_detials);
        ExitApplication.getInstance().addActivity(this);
        initView();
        if (getIntent() != null) {
            processing_id = getIntent().getStringExtra("processing_id");
            netRequest = new NetRequest(this);
            netRequest.requestSubTaskDetails(1, processing_id);
            netRequest.requestLogList(5,processing_id);
        }
    }

    private void initView() {
        netRequest = new NetRequest(this);
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("详情");
        lv = (ListView) findViewById(R.id.lv);

        adapter = new TaskWillSubmitDetialsListAdapter(this, taskDetailsListBeanList, logBeanList, new TaskWillSubmitDetialsListAdapter.OnClickOrder() {
            @Override
            public void changePhoto(TaskDetailsListBean bean, int index) {
                chooseIndex = index;
                getPic();
            }
        });
        lv.setAdapter(adapter);

        public_ll_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ll_cancel = (LinearLayout) findViewById(R.id.ll_cancel);
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ll_submit = (LinearLayout) findViewById(R.id.ll_submit);
        ll_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String jsonData = checkData();
                if(!TextUtils.isEmpty(jsonData)){
                    netRequest.requestTaskProcessingSubmit(2,processing_id,jsonData);
                }
            }
        });
    }

    /**
     * 提交之前检查数据，
     */
    private String checkData(){
        if(taskDetailsListBeanList.size()==0){
            Log.v("zyl","没有数据");
            showToast("请补充完整资料信息!");
            return "";
        }
        JSONArray jsonArray = new JSONArray();
        try {
            for (int i = 0; i < taskDetailsListBeanList.size(); i++) {
                if (TextUtils.isEmpty(taskDetailsListBeanList.get(i).getDocId())) {
                    showToast("请补充完整资料信息!");
                    return "";
                } else {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("path_id", taskDetailsListBeanList.get(i).getDocId() + "");
                    jsonObject.put("title", taskDetailsListBeanList.get(i).getTitle() + "");
                    jsonArray.put(jsonObject);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonArray.toString();
    }

    @Override
    public void onAfinalFail() {
        showToast("请检查本地网络！");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                jsonObject.getString("detail");
                Gson gson = new Gson();
                SubTaskDetailsBean subTaskDetailsBean = gson.fromJson(jsonObject.getString("detail").toString(), SubTaskDetailsBean.class);
                TaskHeadBean taskHeadBean = new TaskHeadBean();
                taskHeadBean.setTv_expiration_date(subTaskDetailsBean.getExpried_date());
                taskHeadBean.setTv_reward(subTaskDetailsBean.getAmount());
                taskHeadBean.setTv_content(subTaskDetailsBean.getDesc1());
                taskHeadBean.setTv_content_title(subTaskDetailsBean.getTask_name());
                taskHeadBean.setPayment_way_key(subTaskDetailsBean.getPayment_way_key());
                adapter.setTaskHeadBean(taskHeadBean);
                if(TextUtils.isEmpty(subTaskDetailsBean.getSubmitted_date())){
                    ifMustMod = true;//是第一次编辑，需要全部修改
                }else{
                    ifMustMod = false;
                }

                Log.v("zyl","ifMustMod:"+ifMustMod);
                Map<String, String> map = Utils.getMapForJson(jsonObject.getString("doc_url"));
                JSONArray jsonArray = new JSONArray(subTaskDetailsBean.getJson_data());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject temJsonObj = jsonArray.getJSONObject(i);
                    String path_id = temJsonObj.getString("path_id");
                    String title = temJsonObj.getString("title");
                    Log.v("zyl","获取到的标题："+title);
                    String url = map.get(path_id);
                    TaskDetailsListBean taskDetailsListBean = new TaskDetailsListBean();
                    taskDetailsListBean.setPicUrl(url);
                    taskDetailsListBean.setTitle(title);
                    //如果必须全部修改的话，则集合不赋值，到时候就得全部上传
                    if(ifMustMod == true){

                    }
                    //如果不用全部修改，则给集合赋值后，集合默认全都有值，到时候就可以绕过检查检验
                    else{
                        Log.v("zyl","添加docId："+path_id);
                        taskDetailsListBean.setDocId(path_id);
                    }
                    taskDetailsListBeanList.add(taskDetailsListBean);
                }
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //提交成功
        else if(requestId == 2){
            EventBus.getDefault().post(new EventBusBean(225));
            EventBus.getDefault().post(new EventBusBean(224));
            showToast("提交成功！");
            finish();
        }
        //上传图片成果
        else if (requestId == 4) {
            if(taskDetailsListBeanList==null){
                return;
            }
            taskDetailsListBeanList.get(tempIndex).setBitmap(bitmapBean.getBitmap());
            try {
                JSONObject object = new JSONObject(result);
                String doc_id = object.getString("doc_id");
                taskDetailsListBeanList.get(tempIndex).setDocId(doc_id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            adapter.notifyDataSetChanged();
        }
        //查询日志
        else if(requestId ==5){
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONArray jsonArray  = jsonObject.getJSONArray("list");
                for (int i = 0;i<jsonArray.length();i++){
                    JSONObject jsonObject1 =  jsonArray.getJSONObject(i);
                    TaskLogBean logBean = new TaskLogBean(jsonObject1.getString("event_desc"), jsonObject1.getString("tracked_date"));
                    logBeanList.add(logBean);
                }
                adapter.notifyDataSetChanged();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showToast(msg);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    Log.v("zyl", "uri.getPath():" + uri.getPath());
                    String path = UtilsBitmap.getImagePathFromUri(this, uri);
                    tempIndex = chooseIndex;
                    bitmapBean = UtilsBitmap.addFilePath3(path, WillSubmitTaskDetailsActivity.this);
                    netRequest.requestUploadPic(4, bitmapBean.getIsBm());
                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {
            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            if (uri != null) {
                UtilsBitmap.getCompressUri(uri);
                String path = UtilsBitmap.getImagePathFromUri(this, uri);
                tempIndex = chooseIndex;
                bitmapBean = UtilsBitmap.addFilePath3(path, WillSubmitTaskDetailsActivity.this);
                netRequest.requestUploadPic(4, bitmapBean.getIsBm());
            }
        }
    }


    public void getPic() {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        dialog = new AlertDialog.Builder(WillSubmitTaskDetailsActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }
                            }
                        }).show();
    }
}
